﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyKho.DKChung;

namespace QuanLyKho.BanHang
{
    public partial class ChiaSPChoCuaHang : Form
    {
        public static string SoChungTu = "0";
        public static string IdSanPham = "0";
        public static bool xem = false;
        public string MaSanPham = "";

        public ChiaSPChoCuaHang()
        {
            InitializeComponent();
            Loaddata();
            SetPropertiesGrid();
            SetPropertiesColumns();
        }

        public void Loaddata()
        {
            if (SoChungTu == "0")
            {
                LoadGrid();
                txtChungtu.Text = "SP" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour
                    + DateTime.Now.Minute + DateTime.Now.Second;
            }
            else
            {
                var data = DataAll.SelectAll("SanPhamTrongCuaHang LEFT JOIN [dbo].[SanPhamHoanThien] ON [SanPhamTrongCuaHang].IDSpHoanThien = [SanPhamHoanThien].ID", "[SanPhamTrongCuaHang].[ID], [SanPhamTrongCuaHang].[IDSpHoanThien] AS'MaSanPham',[IDSpHoanThien],SanPhamTrongCuaHang.[TenCuaHang],SanPhamTrongCuaHang.[NgayChia] ,SanPhamTrongCuaHang.[NguoiChia],SanPhamTrongCuaHang.[NgayChungTu],SanPhamTrongCuaHang.[NgayHoachToan]," +
                "[SanPhamTrongCuaHang].SoChungTu,[SanPhamTrongCuaHang].[SoLuong],[SanPhamTrongCuaHang].[GhiChu], ([SanPhamHoanThien].MaHang+[SanPhamHoanThien].DuoiHang) AS'MaSanPham11',[SanPhamHoanThien].[Size]",
                " WHERE [SanPhamTrongCuaHang].SoChungTu='" + SoChungTu + "'");
                dtNgayChia.Value = Convert.ToDateTime(data.Rows[0]["NgayChia"]);
                luCuaHang.EditValue = data.Rows[0]["TenCuaHang"].ToString();
                luNguoiChia.EditValue = data.Rows[0]["NguoiChia"].ToString();
                dtNgayChungTu.Value = Convert.ToDateTime(data.Rows[0]["NgayChungTu"]);
                dtNgayHachToan.Value = Convert.ToDateTime(data.Rows[0]["NgayHoachToan"]);
                txtChungtu.Text = data.Rows[0]["SoChungTu"].ToString();
                data.Rows.Add();
                gridChiaSP.DataSource = null;
                gridChiaSP.DataSource = data;
                gvChiaSP.OptionsBehavior.Editable = false;
                gcXoa.Visible = false;
            }
        }

        public void SetPropertiesGrid()
        {
            gvChiaSP.OptionsView.ShowGroupPanel = false;
            gvChiaSP.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvChiaSP.OptionsView.ShowFooter = true;
            //gvChiaSP.OptionsBehavior.Editable = false;
            gcSoLuong.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "SoLuong", "{0:0,0}");
            gcSize.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "Size", "{0:0,0}");
            gvChiaSP.Columns["ID"].Visible = false;
            for (int i = 0; i < gvChiaSP.Columns.Count; i++)
            {
                gvChiaSP.Columns[i].OptionsColumn.AllowSort = DefaultBoolean.False;
            }
        }

        public void SetPropertiesColumns()
        {
            gcXoa.Width = 20;
            gcXoa.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            luCuaHang.Properties.DataSource = DataAll.SelectAll("DkChung_CuaHang", "TenCuaHang", ""); ;
            luCuaHang.Properties.Columns.Add(new LookUpColumnInfo("TenCuaHang"));
            luCuaHang.Properties.DisplayMember = "TenCuaHang";
            luCuaHang.Properties.ValueMember = "TenCuaHang";
            luCuaHang.Properties.NullText = string.Empty;
            //luCuaHang.Properties.SearchMode = SearchMode.AutoComplete;
            luCuaHang.Properties.ShowHeader = false;

            var data = DataAll.SelectAll("DkChung_NhanVien", "MaNhanVien,TenNhanVien", "");
            luNguoiChia.Properties.DataSource = data;
            luNguoiChia.Properties.Columns.Add(new LookUpColumnInfo("MaNhanVien"));
            luNguoiChia.Properties.Columns.Add(new LookUpColumnInfo("TenNhanVien"));
            luNguoiChia.Properties.DisplayMember = "TenNhanVien";
            luNguoiChia.Properties.ValueMember = "MaNhanVien";
            luNguoiChia.Properties.Columns["MaNhanVien"].Visible = false;
            luNguoiChia.Properties.NullText = string.Empty;
            luNguoiChia.Properties.TextEditStyle = TextEditStyles.Standard;
            //luNguoiChia.Properties.SearchMode = SearchMode.AutoComplete;
            luNguoiChia.Properties.ShowHeader = false;

            luCatKho.Properties.DataSource = DataAll.SelectAll("Kho_KhoHang", "TenKho", "");
            luCatKho.Properties.Columns.Add(new LookUpColumnInfo("TenKho"));
            luCatKho.Properties.DisplayMember = "TenKho";
            luCatKho.Properties.ValueMember = "TenKho";
            luCatKho.Properties.NullText = string.Empty;
            luCatKho.Properties.ShowHeader = false;

            //luMaSanPham.Properties.DataSource = DataAll.SelectAll("SanPhamHoanThien", "(MaHang+DuoiHang) AS 'MaHang',ID", "");
            //luMaSanPham.Properties.Columns.Add(new LookUpColumnInfo("MaHang"));
            //luMaSanPham.Properties.Columns.Add(new LookUpColumnInfo("ID"));
            //luMaSanPham.Properties.Columns["ID"].Visible = false;
            //luMaSanPham.Properties.DisplayMember = "MaHang";
            //luMaSanPham.Properties.ValueMember = "ID";
            //luMaSanPham.Properties.NullText = string.Empty;
            //luMaSanPham.Properties.TextEditStyle = TextEditStyles.Standard;
            //luMaSanPham.Properties.ShowHeader = false;

            luMaHang.DataSource = SoChungTu == "0" ? DataAll.SelectAll("SanPhamHoanThien", "(MaHang+DuoiHang) AS 'MaAnh',ID", " WHERE SoLuong > 0")
                : DataAll.SelectAll("SanPhamHoanThien", "(MaHang+DuoiHang) AS 'MaAnh',ID", "");
            luMaHang.Columns.Add(new LookUpColumnInfo("MaAnh"));
            luMaHang.Columns.Add(new LookUpColumnInfo("ID"));
            luMaHang.DisplayMember = "MaAnh";
            luMaHang.ValueMember = "ID";
            luMaHang.Columns["ID"].Visible = false;
            luMaHang.NullText = string.Empty;
            luMaHang.TextEditStyle = TextEditStyles.Standard;
            luMaHang.ShowHeader = false;

            luSize.DataSource = DataAll.SelectAll("DkChung_Size", "MaSize", "WHERE Loai=N'Size bình thường'");
            luSize.Columns.Add(new LookUpColumnInfo("MaSize"));
            luSize.DisplayMember = "MaSize";
            luSize.ValueMember = "MaSize";
            luSize.NullText = string.Empty;
            luSize.TextEditStyle = TextEditStyles.Standard;
            luSize.ShowHeader = false;

            luLoaiHang.DataSource = DataAll.SelectAll("PhongMau_LoaiHang", "TenLoaiHang", "");
            luLoaiHang.Columns.Add(new LookUpColumnInfo("TenLoaiHang"));
            luLoaiHang.DisplayMember = "TenLoaiHang";
            luLoaiHang.ValueMember = "TenLoaiHang";
            luLoaiHang.NullText = string.Empty;
            //luLoaiHang.Properties.TextEditStyle = TextEditStyles.Standard;
            luLoaiHang.Properties.ShowHeader = false;
            gcSize.OptionsColumn.AllowEdit = false;

            gcSoLuong.DisplayFormat.FormatType = FormatType.Numeric;
            gcSoLuong.DisplayFormat.FormatString = "{0:0,0}";
        }

        public void LoadGrid()
        {
            var dataColumns = new DataTable();
            dataColumns.Columns.Add("MaSanPham");
            dataColumns.Columns.Add("LanSanXuat");
            dataColumns.Columns.Add("Size");
            dataColumns.Columns.Add("SoLuong", typeof(int));
            dataColumns.Columns.Add("LoaiHang");
            dataColumns.Columns.Add("GhiChu");

            pbAnh.Image = null;
            for (int i = 0; i < 1; i++)
            {
                dataColumns.Rows.Add("");
            }
            gridChiaSP.DataSource = null;
            gridChiaSP.DataSource = dataColumns;
        }

        public bool CheckNull()
        {
            if (cbKho.Checked)
            {
                if (luCatKho.EditValue == null)
                {
                    MessageBox.Show("Bạn phải chọn kho hàng", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            else
            {
                if (luCuaHang.EditValue == null)
                {
                    MessageBox.Show("Bạn phải chọn cửa hàng", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            if (luNguoiChia.EditValue == null)
            {
                MessageBox.Show("Bạn phải chọn người chia", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        public bool CheckSoLuong()
        {
            bool check = true;
            var data = DataAll.SelectAll("SanPhamHoanThien", "*", "");
            for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
            {
                if (gvChiaSP.RowCount > 1)
                {
                    var datacl = (DataView)gvChiaSP.DataSource;
                    DataRow[] soluongmoi = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                    DataRow[] soluongcu = data.Select(" ID='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                    int soluong = 0;
                    for (int j = 0; j < soluongmoi.Length; j++)
                    {
                        if (!string.IsNullOrEmpty(soluongmoi[j]["SoLuong"].ToString()))
                        {
                            soluong += Convert.ToInt32(soluongmoi[j]["SoLuong"].ToString());
                        }
                    }
                    if (Convert.ToInt32(soluongcu[0]["SoLuong"].ToString()) - soluong < 0)
                    {
                        MessageBox.Show("Sản phẩm còn lại không được âm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        check = false;
                        break;
                    }
                    if (cbChiaHet.Checked)
                    {
                        if (Convert.ToInt32(soluongcu[0]["SoLuong"].ToString()) - soluong > 0)
                        {
                            MessageBox.Show("Số lượng sản phẩm cần được chia hết và không âm", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            check = false;
                            break;
                        }
                    }
                }
            }
            return check;
        }

        private void bntLuLai_Click(object sender, EventArgs e)
        {
            if (cbKho.Checked)
            {
                LuuTrongKho();
            }
            else
            {
                if (gvChiaSP.RowCount > 1 && CheckNull() && CheckSoLuong())
                {
                    if (SoChungTu == "0")
                    {
                        string message = string.Empty;
                        var data = DataAll.SelectAll("SanPhamHoanThien", "*", "");
                        for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
                        {
                            DataRow[] soluongcu = data.Select(" ID='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                            var datacl = (DataView)gvChiaSP.DataSource;
                            DataRow[] soluongmoi = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                            int soluong = Convert.ToInt32(soluongcu[0]["SoLuong"].ToString()) - Convert.ToInt32(soluongmoi[0]["SoLuong"].ToString());
                            message = DataAll.Update("SanPhamHoanThien", " SoLuong = " + soluong + " WHERE ID=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                        }
                        for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
                        {
                            //var datasp = DataAll.SelectAll("SanPhamHoanThien", "ID", " WHERE (MaHang+DuoiHang) = '" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                            var cuaHang = DataAll.SelectAll("SanPhamTrongCuaHang", "TenCuaHang", " WHERE TenCuaHang = N'" + luCuaHang.EditValue + "'");
                            if (cuaHang.Rows.Count > 0)
                            {
                                var datadachia = DataAll.SelectAll("SanPhamTrongCuaHang", "IDSpHoanThien", " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                                if (datadachia.Rows.Count <= 0)
                                {
                                    message = DataAll.InsertAll("SanPhamTrongCuaHang", gvChiaSP.GetRowCellValue(i, "MaSanPham") + "," + luCuaHang.EditValue + "," + dtNgayChia.Value.ToString("MM/dd/yyyy")
                                                              + "," + luNguoiChia.EditValue + "," + dtNgayChungTu.Value.ToString("MM/dd/yyyy")
                                                              + "," + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "," + txtChungtu.Text
                                                              + "," + gvChiaSP.GetRowCellValue(i, "SoLuong")
                                                              + "," + gvChiaSP.GetRowCellValue(i, "LoaiHang")
                                                              + "," + gvChiaSP.GetRowCellValue(i, "GhiChu") + "");
                                }
                                else
                                {
                                    var soluongcu = DataAll.SelectAll("SanPhamTrongCuaHang", "SoLuong", " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                                    var slMoi = Convert.ToInt32(gvChiaSP.GetRowCellValue(i, "SoLuong")) + Convert.ToInt32(soluongcu.Rows[0][0]);
                                    message = DataAll.Update("SanPhamTrongCuaHang", "SoLuong = " + slMoi + ", GhiChu = N'" + gvChiaSP.GetRowCellValue(i, "GhiChu") + "'"
                                        + " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                                }
                            }
                            else
                            {
                                message = DataAll.InsertAll("SanPhamTrongCuaHang", gvChiaSP.GetRowCellValue(i, "MaSanPham") + "," + luCuaHang.EditValue + "," + dtNgayChia.Value.ToString("MM/dd/yyyy")
                                                              + "," + luNguoiChia.EditValue + "," + dtNgayChungTu.Value.ToString("MM/dd/yyyy")
                                                              + "," + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "," + txtChungtu.Text
                                                              + "," + gvChiaSP.GetRowCellValue(i, "SoLuong")
                                                              + "," + gvChiaSP.GetRowCellValue(i, "LoaiHang")
                                                              + "," + gvChiaSP.GetRowCellValue(i, "GhiChu") + "");
                            }
                        }
                        MessageBox.Show(message.Equals("success") ? "Chia hàng thành công" : message, "Message",
                                                MessageBoxButtons.OK,
                                                message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    }
                }
            }
        }

        public void LuuTrongKho()
        {
            if (gvChiaSP.RowCount > 1 && CheckNull() && CheckSoLuong())
            {
                if (SoChungTu == "0")
                {
                    string message = string.Empty;
                    var data = DataAll.SelectAll("SanPhamHoanThien", "*", "");
                    for (int i = 0; i < gvChiaSP.RowCount - 1; i++)
                    {
                        DataRow[] soluongcu1 = data.Select(" ID='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                        var datacl = (DataView)gvChiaSP.DataSource;
                        DataRow[] soluongmoi = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                        int soluong = Convert.ToInt32(soluongcu1[0]["SoLuong"].ToString()) - Convert.ToInt32(soluongmoi[0]["SoLuong"].ToString());
                        DataAll.Update("SanPhamHoanThien", " SoLuong = " + soluong + " WHERE ID=" + gvChiaSP.GetRowCellValue(i, "MaSanPham"));

                        //var datasp = DataAll.SelectAll("SanPhamHoanThien", "ID", " WHERE (MaHang+DuoiHang) = '" + gvChiaSP.GetRowCellValue(i, "MaSanPham") + "'");
                        var cuaHang = DataAll.SelectAll("HangTrongKho", "TenKho", " WHERE TenKho = N'" + luCatKho.EditValue + "'");
                        if (cuaHang.Rows.Count > 0)
                        {
                            var datadachia = DataAll.SelectAll("HangTrongKho", "IDSpHoanThien", " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                            if (datadachia.Rows.Count <= 0)
                            {
                                message = DataAll.InsertAll("HangTrongKho", gvChiaSP.GetRowCellValue(i, "MaSanPham") + "," + luCatKho.EditValue
                                                          + "," + dtNgayChia.Value.ToString("MM/dd/yyyy") + "," + dtHanChia.Value.ToString("MM/dd/yyyy")
                                                          + "," + luNguoiChia.EditValue + "," + dtNgayChungTu.Value.ToString("MM/dd/yyyy")
                                                          + "," + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "," + txtChungtu.Text
                                                          + "," + gvChiaSP.GetRowCellValue(i, "SoLuong")
                                                          + "," + gvChiaSP.GetRowCellValue(i, "GhiChu") + "");
                            }
                            else
                            {
                                var soluongcu = DataAll.SelectAll("HangTrongKho", "SoLuong", " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                                var slMoi = Convert.ToInt32(gvChiaSP.GetRowCellValue(i, "SoLuong")) + Convert.ToInt32(soluongcu.Rows[0][0]);
                                message = DataAll.Update("SanPhamTrongCuaHang", "SoLuong = " + slMoi + ", GhiChu = N'" + gvChiaSP.GetRowCellValue(i, "GhiChu") + "'"
                                    + " WHERE IDSpHoanThien = " + gvChiaSP.GetRowCellValue(i, "MaSanPham"));
                            }
                        }
                        else
                        {
                            message = DataAll.InsertAll("HangTrongKho", gvChiaSP.GetRowCellValue(i, "MaSanPham") + "," + luCatKho.EditValue
                                                          + "," + dtNgayChia.Value.ToString("MM/dd/yyyy") + "," + dtHanChia.Value.ToString("MM/dd/yyyy")
                                                          + "," + luNguoiChia.EditValue + "," + dtNgayChungTu.Value.ToString("MM/dd/yyyy")
                                                          + "," + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "," + txtChungtu.Text
                                                          + "," + gvChiaSP.GetRowCellValue(i, "SoLuong")
                                                          + "," + gvChiaSP.GetRowCellValue(i, "GhiChu") + "");
                        }
                    }
                    MessageBox.Show(message.Equals("success") ? "Chia hàng thành công" : message, "Message",
                                            MessageBoxButtons.OK,
                                            message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                }
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        public void LoadImage(string id)
        {
            var MaAnh = DataAll.SelectAll("SanPhamHoanThien", "*", " WHERE ID=" + id + "");
            var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE MaAnh=N'" + MaAnh.Rows[0]["MaHang"] + "'");
            if (data.Rows.Count > 0)
            {
                var content = (byte[])data.Rows[0]["Anh"];
                if (content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(content, 0, content.Length))
                    {
                        ms.Write(content, 0, content.Length);
                        newImage = Image.FromStream(ms, true);
                    }
                    pbAnh.Image = newImage;
                }
                else
                {
                    pbAnh.Image = null;
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void luMaHang_EditValueChanged(object sender, EventArgs e)
        {
        }

        private void gvChiaSP_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Caption == "Mã sản phẩm")
            {
                if (e.RowHandle == gvChiaSP.RowCount - 1)
                {
                    (gridChiaSP.MainView as GridView).AddNewRow();
                }
                //var maHang = (DataRowView)luMaHang.GetDataSourceRowByKeyValue(gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham"));
                var data = DataAll.SelectAll("SanPhamHoanThien", "*", " WHERE ID = " + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "");
                gvChiaSP.SetRowCellValue(e.RowHandle, "Size", data.Rows[0]["Size"].ToString());
                txtMaSanPham.Text = gvChiaSP.GetRowCellDisplayText(e.RowHandle, "MaSanPham");
                txtIdSP.Text = gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham").ToString();
                txtSoLuong.Text = data.Rows[0]["SoLuong"].ToString();
                txtLoaiHang.Text = data.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = data.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = data.Rows[0]["LenhSanXuat"].ToString();
                dtNgayLL.Value = Convert.ToDateTime(data.Rows[0]["NgayLL"].ToString());
                LoadImage(data.Rows[0]["ID"].ToString());
                //check use
                var datanhap = (DataView)gvChiaSP.DataSource;
                if (datanhap.Count > 2)
                {
                    for (int i = 0; i < datanhap.Count - 1; i++)
                    {
                        if (i != e.RowHandle)
                        {
                            if (gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham").ToString() == datanhap.Table.Rows[i]["MaSanPham"].ToString())
                            {
                                MessageBox.Show("Nhập trùng giá trị " + gvChiaSP.GetRowCellDisplayText(e.RowHandle, "MaSanPham"), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                if (e.RowHandle == gvChiaSP.RowCount - 2)
                                {
                                    (gridChiaSP.MainView as GridView).DeleteRow(e.RowHandle);
                                }
                                else
                                {
                                    gvChiaSP.SetRowCellValue(e.RowHandle, "MaSanPham", "");
                                }
                                break;
                            }
                        }
                    }
                }
                //so luong con lai
                var datacl = (DataView)gvChiaSP.DataSource;
                DataRow[] result = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    if (!string.IsNullOrEmpty(result[i]["SoLuong"].ToString()))
                    {
                        soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                    }
                }
                txtConLai.Text = Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong);
            }
            if (e.Column.Caption == "Số lượng")
            {
                var data = (DataView)gvChiaSP.DataSource;
                DataRow[] result = data.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                }
                txtConLai.Text = Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong);
            }
        }

        private void pbAnh_Click(object sender, EventArgs e)
        {
            var MaAnh = DataAll.SelectAll("SanPhamHoanThien", "MaHang", " WHERE ID=" + txtIdSP.Text);
            XemAnh.MaID = MaAnh.Rows[0]["MaHang"].ToString();
            var anh = new XemAnh();
            anh.ShowDialog();
            XemAnh.MaID = "0";
        }

        private void cbKho_CheckedChanged(object sender, EventArgs e)
        {
            luCatKho.Enabled = cbKho.Checked;
            dtHanChia.Enabled = cbKho.Checked;
            luCuaHang.Enabled = !cbKho.Checked;
        }

        private void gvChiaSP_RowClick(object sender, RowClickEventArgs e)
        {
            if (gvChiaSP.RowCount > 1 && e.RowHandle < gvChiaSP.RowCount - 1)
            {
                var data = DataAll.SelectAll("SanPhamHoanThien", "*", " WHERE ID = " + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "");
                gvChiaSP.SetRowCellValue(e.RowHandle, "Size", data.Rows[0]["Size"].ToString());
                txtMaSanPham.Text = gvChiaSP.GetRowCellDisplayText(e.RowHandle, "MaSanPham");
                txtIdSP.Text = gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham").ToString();
                txtSoLuong.Text = data.Rows[0]["SoLuong"].ToString();
                txtLoaiHang.Text = data.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = data.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = data.Rows[0]["LenhSanXuat"].ToString();
                LoadImage(data.Rows[0]["ID"].ToString());
                //so luong con lai
                var datacl = (DataView)gvChiaSP.DataSource;
                DataRow[] result = datacl.Table.Select(" MaSanPham='" + gvChiaSP.GetRowCellValue(e.RowHandle, "MaSanPham") + "'");
                int soluong = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    if (!string.IsNullOrEmpty(result[i]["SoLuong"].ToString()))
                    {
                        soluong += Convert.ToInt32(result[i]["SoLuong"].ToString());
                    }
                }
                txtConLai.Text = SoChungTu == "0" ? Convert.ToString(Convert.ToInt32(txtSoLuong.Text) - soluong) : "0";
            }
        }

        private void buttonDelete_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gvChiaSP.FocusedRowHandle == gvChiaSP.RowCount - 1)
            {
                return;
            }

            DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn xóa.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dialogResult == DialogResult.Yes)
            {
                (gridChiaSP.MainView as GridView).DeleteSelectedRows();
            }
        }
    }
}
